<?php
/**
 * 车主补偿数据处理
 * @author angl
 */

date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db()
{
    $db = new MysqliDb ([
        'host' => MYSQLDB,
        'username' => MYSQLDB_USER,
        'password' => MYSQLDB_PWD,
        'db' => MYSQLDB_DATABASE,
        'port' => 3306,
        'prefix' => 'au_',
        'charset' => 'utf8'
    ]);
    return $db;
}

$db = init_db();
$counter = 0;

while (true){
    //获取
    $list = $db->where('status',2)->where('deal_time','2016-12-20','<')->get('breach_car');
    //循环处理
    foreach ($list as $key=>$item){
        if($item['collection_id'] > 0){
            $db->where('id',$item['collection_id'])->update('collection',['status'=>-2]);
        }
        if($item['collection_id_car'] > 0){
            $db->where('id',$item['collection_id_car'])->update('collection',['status'=>-2]);
        }
        if($item['payment_id'] > 0){
            $db->where('id',$item['payment_id'])->update('payment',['status'=>-2]);
        }
        $is_pay = $db->where('car_id',$item['car_id'])->where('action_no',5003)->getOne('car_trace_log_list');
        if(!empty($is_pay)){  //已付
            $pay = $db->where('car_id',$item['car_id'])->getOne("pay_log");
            $collection = $db->where('id',$item['collection_id_car'])->getOne("collection");
            $refund = $db->where('car_id',$item['car_id'])->getOne('receivable_refund');
            //收款信息            
            $carCollectionData = [];
            $carCollectionData['payment_type'] = 7;
            $carCollectionData['payment_method'] = 1;
            $carCollectionData['refer'] = 1;
            $carCollectionData['collection_no'] = genBillsNo("SK",7,$item['deal_time']);
            //如果没有应收退款信息
            if (empty($refund)){
                $carCollectionData['status'] = 1;
                $carCollectionData['create_time'] = $item['deal_time'];
                $carCollectionData['update_time'] = $item['deal_time'];
                $carCollectionData['emp_id'] = 31;
                $carCollectionData['emp_name'] = "系统";
            }else{
                if($refund['status']>1){
                    $carCollectionData['status'] = 1 ;
                    $carCollectionData['emp_id'] = $refund['emp_id'] ;
                    $emp = $db->where('emp_id',$refund['emp_id'])->getOne('employee');
                    $carCollectionData['emp_name'] = $emp['real_name'];
                    $carCollectionData['create_time'] = $refund['createtime'];
                    $carCollectionData['update_time'] = $refund['receivable_time'];
                }else{
                    $carCollectionData['status'] = 0 ;
                    $carCollectionData['create_time'] = $refund['createtime'];
                }
            }
            //补偿扣除金额为0的数据
            if($item['compensate'] == 0){
                $carCollectionData['amount'] = $pay['amount'];
            }else{
                if($item['back_method'] == 0 || $item['back_method'] == 1){
                    $carCollectionData['amount'] = $pay['amount'] - $item['compensate'];
                }else{
                    $collectionData = $carCollectionData;
                    $collectionData['amount'] = $item['compensate'];
                    $collectionData['payment_type'] = 8;
                    $collectionData['collection_no'] = genBillsNo("SK", 8, $item['deal_time']);
                    if($item['collection_id']>0){
                        $db->where('id',$item['collection_id'])->update('collection', $collectionData);
                        logUtil("已付，更新应收车主违约金收款记录 {$item['car_id']}");
                    }else{
                        $collectionData['branch_id'] = getBranchIdByCarId($item['car_id']);
                        $collectionId = $db->insert('collection',$collectionData);
                        $db->where("bc_id", $item['bc_id'])->update('breach_car', ['collection_id' => $collectionId]);
                        logUtil("已付，新增应收车主违约金收款记录 {$item['car_id']}");
                    }
                }
            }
            if(!empty($collection)){ //已经生成收款信息，更新
                $db->where('id',$collection['id'])->update('collection', $carCollectionData);
                logUtil("已付，更新 车主应收退款 收款记录 {$item['car_id']}");
            }else{ //没有生成收款信息，新增
                $carCollectionData['branch_id'] = getBranchIdByCarId($item['car_id']);
                $collectionId = $db->insert('collection',$carCollectionData);
                $db->where("bc_id", $item['bc_id'])->update('breach_car', ['collection_id_car' => $collectionId]);
                logUtil("已付，新增 车主应收退款收款记录 {$item['car_id']}");
            }
        }else{  //未付
            if($item['compensate'] > 0){
                if($item['back_method'] == 0 || $item['back_method'] == 1){ //检测失误
                    $paymentData = [];
                    $paymentData['pay_type'] = 6; //车主补偿
                    $paymentData['pay_way'] = 2;
                    $paymentData['amount'] = $item['compensate'];
                    $paymentData['refer'] = 1;
                    $paymentData['branch_id'] = getBranchIdByCarId($item['car_id']);

                    //查找车主补偿
                    $caOwnerCompensate = $db->where('car_id',$item['car_id'])->getOne('car_owner_compensate');
                    if(empty($caOwnerCompensate)){
                        $paymentData['status'] = 1;
                        $paymentData['create_time'] = $item['deal_time'];
                        $paymentData['update_time'] = $item['deal_time'];
                        $paymentData['emp_id'] = 31;
                        $paymentData['emp_name'] = "系统";
                    }else{
                        if($caOwnerCompensate['status']>1){
                            $paymentData['status'] = 1;
                            $paymentData['create_time'] = $caOwnerCompensate['createtime'];
                            $paymentData['update_time'] = $caOwnerCompensate['compensate_time'];
                            $paymentData['emp_id'] = $caOwnerCompensate['emp_id'];
                            $emp = $db->where('emp_id',$caOwnerCompensate['emp_id'])->getOne('employee');
                            $paymentData['emp_name'] = $emp['real_name'];
                        }else{
                            $paymentData['create_time'] = $caOwnerCompensate['createtime'];
                            $paymentData['status'] = 0;
                        }
                    }
                    $paymentData['payment_no'] = genBillsNo("FK", $paymentData['pay_type'], $paymentData['create_time']);
                    if($item['payment_id'] > 0){
                        //$paymentInfo = $db->where('id',$item['payment_id'])->getOne("payment");
                        //$paymentData['status'] = $paymentInfo['status'];
                        $db->where('id',$item['payment_id'])->update('payment',$paymentData);
                        logUtil("未付，检测失误赔付车主，更新付款信息 {$item['car_id']}");
                    }else{
                        $paymentId = $db->insert("payment",$paymentData);
                        $db->where("bc_id", $item['bc_id'])->update('breach_car', ['payment_id' => $paymentId]);
                        logUtil("未付，检测失误赔付车主，新增付款信息 {$item['car_id']}");
                    }
                }else{ //补偿
                    $collectionData = [];
                    $collectionData['payment_type'] = 8;
                    $collectionData['payment_method'] = 1;
                    $collectionData['amount'] = $item['compensate'];
                    $collectionData['refer'] = 1;
                    $collectionData['collection_no'] = genBillsNo("SK",8,$item['deal_time']);
                    $refund = $db->where('car_id',$item['car_id'])->getOne('receivable_refund');
                    //如果没有应收退款信息
                    if (empty($refund)){
                        $collectionData['status'] = 1;
                        $collectionData['create_time'] = $item['deal_time'];
                        $collectionData['update_time'] = $item['deal_time'];
                        $collectionData['emp_id'] = 31;
                        $collectionData['emp_name'] = "系统";
                    }else{
                        if($refund['status']>1){
                            $collectionData['status'] = 1 ;
                            $collectionData['emp_id'] = $refund['emp_id'] ;
                            $emp = $db->where('emp_id',$refund['emp_id'])->getOne('employee');
                            $collectionData['emp_name'] = $emp['real_name'];
                            $collectionData['create_time'] = $refund['createtime'];
                            $collectionData['update_time'] = $refund['receivable_time'];
                        }else{
                            $collectionData['status'] = 0 ;
                            $collectionData['create_time'] = $refund['createtime'];
                        }
                    }
                    if($item['collection_id'] > 0){ //如果已经生成收款信息
                        $db->where('id',$item['collection_id'])->update('collection',$collectionData);
                        logUtil("未付，车主原因 应收车主，更新收款信息 {$item['car_id']}");
                    }else{
                        $collectionId = $db->insert('collection',$collectionData);
                        $db->where("bc_id", $item['bc_id'])->update('breach_car', ['collection_id' => $collectionId]);
                        logUtil("未付，车主原因 应收车主，更新收款信息 {$item['car_id']}");
                    }
                }
            }
        }
        $counter++;
    }
    logUtil($counter." 条数据处理完成","INFO");
    exit;
}

function getRefundCar($car_id)
{
    global $db;
    return $db->where('car_id', $car_id)->where("status",3)->getOne("refund_car");
}

function getPaymentData($id)
{
    global $db;
    return $db->where('id',$id)->getOne("payment");
}


function getBranchIdByCarId($carId)
{
    global $db;
    $carInfo = $db->where('car_id',$carId)->getOne('cars');
    $branchInfo = $db->where("city_code",$carInfo['location_area'])->getOne("branch_city");
    return $branchInfo['branch_id'];
}

/**
 * 产生固定长度的随机字符串
 * @param $len
 * @param null $chars
 * @return string
 */
function genRandomChars($len, $chars = null)
{
    if (is_null($chars)) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }
    mt_srand(10000000 * (double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}

/**
 * 产生一个四位的随机字符串
 * @return string
 */
function gen4Chars()
{
    $strChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $numbers = "0123456789";
    $randomString = genRandomChars(3);
    if (ctype_digit($randomString)) {
        $randomString = $randomString . genRandomChars(1, $strChars);
    } elseif (ctype_alpha($randomString)) {
        $randomString = $randomString . genRandomChars(1, $numbers);
    } else {
        $randomString = $randomString . genRandomChars(1);
    }
    return $randomString;
}

function genBillsNo($type, $subType, $date='')
{
    if ($subType < 10) $subType = "0" . $subType;
    if($date!==''){
        $date = date("Ymd",strtotime($date));
    }else{
        $date = date("Ymd");
    }
    return $type . $subType . $date . gen4Chars();
}